import { PlusOutlined } from '@ant-design/icons';
import { Button, Space, Table, TableProps } from 'antd';
import { Pagination } from 'antd/lib';
import { useEffect, useState } from 'react';
import styles from './index.less';

interface Props {
  columns: TableProps['columns'];
  title: string;
  buttonText: string;
  buttonAction: () => void;
  loading: boolean;
  data: any[];
  rowClassName?: (record: any) => string;
}
export default function ProTable(props: Props) {
  const {
    title,
    buttonText,
    buttonAction,
    columns,
    loading,
    data,
    rowClassName,
  } = props;
  const [currentList, setCurrentList] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);

  useEffect(() => {
    setCurrentList(
      data.slice((currentPage - 1) * pageSize, currentPage * pageSize),
    );
  }, [currentPage, pageSize, loading]);

  const handleShowSizeChange = (current: number, size: number) => {
    if (current !== currentPage) {
      setCurrentPage(current);
    }
    if (size !== pageSize) {
      setPageSize(size);
      setCurrentPage(1);
    }
  };

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>{title}</h1>
      <Space className={styles.create}>
        <Button
          type="primary"
          onClick={buttonAction}
          icon={<PlusOutlined />}
          className={styles.createBtn}
        >
          {buttonText}
        </Button>
      </Space>
      <div className={styles.table}>
        <Table
          columns={columns}
          dataSource={currentList}
          loading={loading}
          rowClassName={rowClassName}
          scroll={{ x: true }}
          pagination={false}
        />
        {!loading && (
          <Pagination
            showSizeChanger
            pageSizeOptions={['10', '20', '50', '100']}
            pageSize={pageSize}
            total={data.length}
            onChange={handleShowSizeChange}
            locale={{ items_per_page: '/ 页' }}
          />
        )}
      </div>
    </div>
  );
}
